﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using TodoApi.Models;

namespace TodoApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [AllowAnonymous]
    public class LoginController : ControllerBase
    {
        private readonly StudentContext _context;
        private readonly IConfiguration _configuration;
        public LoginController(StudentContext context,IConfiguration configuration)
        {
            _context = context;
            _configuration = configuration;
        }
        [HttpPost]
        public string  Login(User user)
        {
            if(_context.User.Any(x=>x.Account == user.Account))
            {
                var result = _context.User.Include(x=>x.Role).Where(x => x.Account == user.Account && x.PassWord == user.PassWord).FirstOrDefault();
                if (result == null)
                {
                    return "账号或者密码错误";
                }
                else
                {
                    var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name, result.Account),
                        new Claim("昵称", result.Name),
                        new Claim(ClaimTypes.Role,result.Role.Name)
                    };
                    var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    //var authProperties = new AuthenticationProperties() { ExpiresUtc = DateTime.UtcNow.AddMinutes(30) };
                    //HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
                    HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
                    return "登录成功";
                }
            }
            else
            {
                return "账号不存在";
            }
        }
        [HttpPost]
        public string JWTLogin(User user)
        {
            if (_context.User.Any(x => x.Account == user.Account))
            {
                var result = _context.User.Include(x => x.Role).Where(x => x.Account == user.Account && x.PassWord == user.PassWord).FirstOrDefault();
                if (result == null)
                {
                    return "账号或者密码错误";
                }
                else
                {
                    var claims = new List<Claim>
                    {
                        new Claim(JwtRegisteredClaimNames.Email, result.Account),
                        new Claim("昵称", result.Name),
                        new Claim(ClaimTypes.Role,result.Role.Name)
                    };
                    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Key"]));
                    var jwt = new JwtSecurityToken
                    (
                        issuer: _configuration["JWT:Issuer"],
                        audience: _configuration["JWT:Audience"],
                        claims:claims,
                        //有效时间
                        expires:DateTime.Now.AddMinutes(30),
                        signingCredentials:new SigningCredentials(securityKey,SecurityAlgorithms.HmacSha256)
                    );
                    var token = new JwtSecurityTokenHandler().WriteToken(jwt);
                    return token;
                }
            }
            else
            {
                return "账号不存在";
            }
        }
        [HttpPost]
       public string  CreateLogin(User user)
        {
            if (_context.User.Any(x => x.Account == user.Account))
            {
                return "账号已存在";
            }
            user.Id = Guid.NewGuid();
            user.Role = _context.Role.Where(x => x.Name == "用户").FirstOrDefault();
            _context.User.Add(user);
            _context.SaveChanges();
            return "创建账号成功";
        }
        [HttpDelete]
        public string Logout()
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return "成功退出登录";
        }
        [HttpGet]
        public string NoLogin()
        {
            return "未登录";
        }
        [HttpGet]
        public string NoRole()
        {
            return "用户没有权限";
        }
    }
}
